import { Dropdown } from "antd";
import { MenuItemType } from "antd/es/menu/interface";
import React, { Children, useCallback, useMemo } from "react";

import { antdIcons } from "@/assets/antd-icons";
import DraggableTab from "@/components/draggable-tab";
import { defaultSetting } from "@/default-setting";
import { KeepAliveTab, useTabs } from "@/hooks/use-tabs";
import { router } from "@/router";
import { t } from "@/utils/i18n";
import { arrayMove } from "@dnd-kit/sortable";

import { KeepAliveTabContext } from "./tabs-context";
import Watermark from "./watermark";

enum OperationType {
    REFRESH = "refresh",
    CLOSE = "close",
    CLOSE_OTHER = "close-other",
}

// TODO ??? React.FC
const TabsLayout: React.FC = () => {
    const {
        //
        activeTabRoutePath,
        tabs = [],
        closeTab,
        refreshTab,
        closeOtherTab,
        setTabs,
    } = useTabs();

    const getIcon = (icon?: string): React.ReactElement | undefined => {
        return icon && antdIcons[icon] && React.createElement(antdIcons[icon]);
    };

    // ??? menuItems 干嘛的
    const menuItems: MenuItemType[] = useMemo(
        () =>
            [
                {
                    label: t("slZKRXqL" /* 刷新 */),
                    key: OperationType.REFRESH,
                },
                tabs.length <= 1
                    ? null
                    : {
                          label: t("FplLzQwk" /* 关闭 */),
                          key: OperationType.CLOSE,
                      },
                tabs.length <= 1
                    ? null
                    : {
                          label: t("JPlYJWgB" /* 关闭其他 */),
                          key: OperationType.CLOSE_OTHER,
                      },
            ].filter((k) => k !== null) as MenuItemType[],
        [tabs],
    );

    const menuClick = useCallback(
        ({ key, domEventy }: any, tab: KeepAliveTab) => {
            domEventy.stopPropagation();
            if (key === OperationType.REFRESH) {
                refreshTab(tab.routePath);
            } else if (key === OperationType.CLOSE) {
                closeTab(tab.routePath);
            } else if (key === OperationType.CLOSE_OTHER) {
                closeOtherTab(tab.routePath);
            }
        },
        [closeOtherTab, closeTab, refreshTab],
    );

    const renderTabTitle = useCallback(
        (tab: KeepAliveTab) => {
            return (
                <Dropdown
                    menu={{
                        items: menuItems,
                        onClick: (e) => menuClick(e, tab),
                    }}
                    trigger={["contextMenu"]}
                    onOpenChange={(open) => {
                        if (open) {
                            router.navigate(tab.pathname);
                        }
                    }}
                >
                    <div
                        className="flex gap-[6px]"
                        style={{ margin: "-12px 0", padding: "12px 0" }}
                    >
                        {getIcon(tab.icon)}
                        {tab.title}
                    </div>
                </Dropdown>
            );
        },
        [menuItems],
    );

    const tabItems = useMemo(() => {
        return tabs.map((tab) => {
            return {
                key: tab.routePath,
                label: renderTabTitle(tab),
                children: (
                    <div
                        key={tab.key}
                        className="overflow-y-auto"
                        style={{
                            height: `calc(100vh - ${defaultSetting.headerHeight + 36}px)`,
                        }}
                    >
                        <Watermark type="content">{tab.children}</Watermark>
                    </div>
                ),
                closable: tabs.length > 1, // 不能删除最后一个
            };
        });
    }, [tabs]);
    const onTabsChange = useCallback((tabRoutePath: string) => {
        router.navigate(tabRoutePath);
    }, []);

    const onTabEdit = (targetKey: React.MouseEvent | React.KeyboardEvent | string, action: "add" | "remove") => {
        if (action === "remove") {
            closeTab(targetKey as string);
        }
    };

    const keepAliveContextValue = useMemo(
        () => ({
            closeTab,
            closeOtherTab,
            refreshTab,
        }),
        [closeTab, closeOtherTab, refreshTab],
    );

    return (
        <KeepAliveTabContext.Provider value={keepAliveContextValue}>
            <DraggableTab
                activeKey={activeTabRoutePath}
                items={tabItems}
                type="editable-card"
                onChange={onTabsChange}
                hideAdd
                onEdit={onTabEdit}
                size="small"
                onDragEnd={({ activeIndex, overIndex }) => {
                    setTabs(arrayMove(tabs, activeIndex as number, overIndex as number));
                }}
            />
        </KeepAliveTabContext.Provider>
    );
};

export default TabsLayout;
